package com.project.petLossSystem.controller.common;

import com.project.petLossSystem.common.CustomException;
import com.project.petLossSystem.util.ResultGenerator;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionController {

    @ExceptionHandler(Exception.class)
    public Object exceptionHandler(HttpServletRequest request, Exception e) {
        // 判断请求类型，即返回封装类还是视图
        // AJAX请求
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            // 判断是否为自定义异常
            if (e instanceof CustomException) {
                return ResultGenerator.failureResult(e.getMessage());
            } else {
                e.printStackTrace();
                return ResultGenerator.failureResult("未知异常！");
            }
        } else {
            ModelAndView modelAndView = new ModelAndView("/pc/error/error");
            // 判断是否为自定义异常
            if (e instanceof CustomException) {
                modelAndView.addObject("reason", e.getMessage());
            } else {
                modelAndView.addObject("reason", "未知异常！");
                e.printStackTrace();
            }
            return modelAndView;
        }
    }
}
